//
//  DataBaseOperator.m
//  MarketDataColloctor
//
//  Created by jiro on 10/01/14.
//  Copyright 2010 jiro music. All rights reserved.
//

#import <Cocoa/Cocoa.h>
#import "DbOperator.h"
#import "../DbTypes/DbConstants.h"

@implementation DbOperator

- (id) init
{
	self = [ super init ];
	errorMessage = @"";
	dbConnection = nil;
	return self;
}

+ (DbOperator*) defaultOperator
{
	DbOperator* dbOperator = [ [ DbOperator alloc ] init ];
	[ dbOperator connectToDb: kText_DefaultDb ofHost: kText_DefaultHost asUser: kText_DefaultUserName ];
	return dbOperator;
}

- (BOOL) connectToDb: (NSString*) databaseName ofHost: (NSString*) host asUser: (NSString*) userName
{
	NSString* connectionInfo = [ NSString stringWithFormat: @"host=%@ dbname=%@ user=%@", host, databaseName, userName ];
	dbConnection = PQconnectdb( [ connectionInfo cStringUsingEncoding: NSUTF8StringEncoding ] );

	if ( CONNECTION_OK != PQstatus( dbConnection ) )
	{
		errorMessage = [ NSString stringWithCString: PQerrorMessage( dbConnection ) encoding: NSUTF8StringEncoding ];
		return NO;
	}

	return YES;
}

- (void) disconnect
{
	if ( dbConnection != nil )
	{
		PQfinish( dbConnection );
	}
}

- (DbResponseType) executeQuery: (NSString*) query intoResult: (PGresult**) result
{
	if ( CONNECTION_OK != PQstatus( dbConnection ) )
	{
		errorMessage = [ NSString stringWithCString: PQerrorMessage( dbConnection ) encoding: NSUTF8StringEncoding ];;
		return DbResponse_Fail;
	}

	*result = PQexec( dbConnection, [ query cStringUsingEncoding: NSUTF8StringEncoding ] );
	if ( *result == nil )
	{		
		errorMessage = [ NSString stringWithCString: PQerrorMessage( dbConnection ) encoding: NSUTF8StringEncoding ];;
		return DbResponse_Fail;
	}
	
	ExecStatusType statusType = PQresultStatus( * result );
	switch ( statusType ) {
	case PGRES_EMPTY_QUERY:
	case PGRES_COMMAND_OK:
	case PGRES_TUPLES_OK:
	case PGRES_COPY_OUT:
	case PGRES_COPY_IN:
		return DbResponse_Success;
	case PGRES_NONFATAL_ERROR:
		errorMessage = [ NSString stringWithCString: PQerrorMessage( dbConnection ) encoding: NSUTF8StringEncoding ];;
		return DbResponse_SuccessWithWarning;
	case PGRES_FATAL_ERROR:
		errorMessage = [ NSString stringWithCString: PQerrorMessage( dbConnection ) encoding: NSUTF8StringEncoding ];;
		return DbResponse_Fail;
	case PGRES_BAD_RESPONSE:
	default:
		errorMessage = [ NSString stringWithCString: PQerrorMessage( dbConnection ) encoding: NSUTF8StringEncoding ];;
		return DbResponse_Unknown;
	}
}

- (DbResponseType) executeQueries: (const std::vector< NSString* >&) queries intoResults: (std::vector< PGresult* >&) results;
{
	DbResponseType response;
	for ( int i = 0, count = queries.size(); i < count; i++ )
	{
		PGresult* r;
		NSString* s = queries[ i ];
		response = [ self executeQuery: s intoResult: & r ];
		results.push_back( r );
		if ( response != DbResponse_Success )
		{
			break;
		}
	}
	return response;
}

- (NSString*) errorMessage
{
	return errorMessage;
}

@end
